package cn.itsource.exam.controller;

import cn.itsource.exam.domain.Exam;
import cn.itsource.exam.domain.Login;
import cn.itsource.exam.domain.StudentInfo;
import cn.itsource.exam.query.ExamResultQuery;
import cn.itsource.exam.service.StudentService;
import cn.itsource.exam.util.AjaxResult;
import cn.itsource.exam.util.Md5Helper;
import cn.itsource.exam.util.PageList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * Created by xiong on 2020/7/8.
 */
@RestController
@RequestMapping("/student")
public class StudentController {
    @Autowired
    StudentService studentService;

    @PostMapping("/list")
    public PageList<Exam> selectExamList(@RequestBody ExamResultQuery map, HttpServletRequest request){
        String uToken = request.getHeader("U-TOKEN");
        Login userInfo = (Login) request.getSession().getAttribute(uToken);
        map.setId(userInfo.getId().toString());
        PageList<Exam> list = studentService.selectExam(map);
        return list;
    }

    @PostMapping("/student")
    public AjaxResult changePwd(@RequestBody Map map, HttpServletRequest request){
        try {
            String uToken = request.getHeader("U-TOKEN");
            Login userInfo =(Login) request.getSession().getAttribute(uToken);
            Login user = studentService.selectById(userInfo.getId());
            String newPwd = map.get("newPwd").toString();
            String oldPwd = map.get("oldPwd").toString();

            String password = Md5Helper.MD5(oldPwd);
            if (user == null) {
                return  AjaxResult.error("用户不存在或状态异常，请重新登录！");
            }
            if (!password.equals(user.getPassword())) {
                return  AjaxResult.error("旧密码不正确！");
            }
            user.setPassword(Md5Helper.MD5(newPwd));
            studentService.updatePwdById(user);
        }catch (Exception e){
            return AjaxResult.error("修改失败重新登录再试！");
        }
        return AjaxResult.success();
    }

}
